package com.jsptpd.smartauth.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

@Component
public class JWTUtil {
    /**
     * APP登录Token的生成和解析
     *
     */

    /** token秘钥，请勿泄露，请勿随便修改*/
    public static final String JWT_SECRET = "JWT5490jk1k";
    /** token 过期时间: 100天 */
    public static final int calendarField = Calendar.DATE;

    public static int jwtExpire = 100;

    @Value("${config.jwt.expire}")
    private int jwtExpireConfig;

    @PostConstruct
    public void getJwtExipre() {
        jwtExpire = this.jwtExpireConfig;
    }

    /**
     * JWT生成Token.
     *
     * JWT构成: header, payload, signature

     */
    public static String createToken(String appName, String userId) throws Exception {
        Date iatDate = new Date();
        // expire time
        Date expiresDate = DateUtil.getNewDate(iatDate,jwtExpire,Calendar.HOUR);

        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        // param backups {iss:Service, aud:APP}
        String token = JWT.create().withHeader(map) // header
                .withClaim("appName", appName) // payload
                .withClaim("userId", null == userId ? "" : userId)
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(JWT_SECRET)); // signature

        return token;
    }

    /**
     * 解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JWT_SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            // token 校验失败, 抛出Token验证非法异常
            // e.printStackTrace();
            return null;
        }
        return jwt.getClaims();
    }

    /**
     * 根据Token获取user_id
     *
     * @param token
     * @return user_id
     */
    public static String getAppUID(String token) {
        Map<String, Claim> claims = verifyToken(token);
        if(claims!=null && claims.get("userId")!=null) {
            Claim user_id_claim = claims.get("userId");
            if (null == user_id_claim || "".equals(user_id_claim.asString())) {
                // token 校验失败, 抛出Token验证非法异常
                return "";
            }
            return user_id_claim.asString();
        }else{
            return "";
        }
    }
}

